import React,{useState,useEffect,useRef} from 'react'
import axios from 'axios'
function App() {
    let [index1,setIndex] = useState(0)
   let [arr,setArr] = useState([])
   let myref = useRef(null)
   useEffect(()=>{
        axios.get("/api/floorlist").then(res=>{
            setArr(res.data)
        })
        setTimeout(() => {
            // 监听页面的滚动事件
            window.addEventListener("scroll",handscroll,true)
        }, 200);
   },[])
   let handscroll = ()=>{
       let topS = myref.current.scrollTop  // 右侧盒子滚动的距离
       console.log(topS);
       let arr = Array.from(myref.current.children) // 将类数组转换为真正的数组
       arr.forEach((item,index)=>{   // 右侧滚动的离大于了子盒子距离顶部的距离他就该高亮了
           if (topS > item.offsetTop) {
               setIndex(index)
           }
       })
   }
   let changeIndex = (index)=>{
        console.log(index);
        setIndex(index)
        console.log(myref.current.children);
        // scrollIntoView 让一个元素滚动到浏览器的最顶部
        myref.current.children[index].scrollIntoView({behavior:"smooth"})
   }
  return (
    <div className='wrap'>
        <div className='left'>
            {
                arr && arr.length ? arr.map((item,index)=>{
                    return <h3 key={index} onClick={()=>changeIndex(index)} className={index===index1+1?"active":""}>{item.tit}</h3>
                }):""
            }

        </div>
        <div className='right' ref={myref}>
            {
                arr && arr.length ? arr.map((item,index)=>{
                    return ( // 小括号表示可以换行
                        <div>
                            <h3>{item.tit}</h3>
                            <div className='dlbox'>
                                {
                                    item.children &&  item.children.length ?  item.children.map((ite,ind)=>{
                                        return <dl key={ind}>
                                            <dd>
                                                {/* 在react里写图片必须有alt，没有alt出不来 */}
                                                <img src={ite.img} alt="" />
                                            </dd>
                                            <dt>{ite.tit}</dt>
                                        </dl>
                                    }):""
                                }
                            </div>
                        </div>
                    )
                }):""
            }
        </div>
    </div>
  )
}

export default App